﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Party.PartyComponents.CaravanPartyComponent
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.Extensions;
using TaleWorlds.CampaignSystem.Roster;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Party.PartyComponents
{
  public class CaravanPartyComponent : PartyComponent
  {
    public const int DefaultCaravanPartyTradeInitialGold = 10000;
    [CachedData]
    private TextObject _cachedName;
    [SaveableField(3)]
    private Hero _leader;

    internal static void AutoGeneratedStaticCollectObjectsCaravanPartyComponent(
      object o,
      List<object> collectedObjects)
    {
      ((PartyComponent) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
    }

    protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
    {
      base.AutoGeneratedInstanceCollectObjects(collectedObjects);
      collectedObjects.Add((object) this._leader);
      collectedObjects.Add((object) this.Settlement);
      collectedObjects.Add((object) this.Owner);
    }

    internal static object AutoGeneratedGetMemberValueSettlement(object o)
    {
      return (object) ((CaravanPartyComponent) o).Settlement;
    }

    internal static object AutoGeneratedGetMemberValueOwner(object o)
    {
      return (object) ((CaravanPartyComponent) o).Owner;
    }

    internal static object AutoGeneratedGetMemberValue_leader(object o)
    {
      return (object) ((CaravanPartyComponent) o)._leader;
    }

    [SaveableProperty(1)]
    public Settlement Settlement { get; private set; }

    [SaveableProperty(2)]
    public Hero Owner { get; private set; }

    public override Hero PartyOwner => this.Owner;

    public override TextObject Name
    {
      get
      {
        if (this._cachedName == null)
        {
          this._cachedName = GameTexts.FindText("str_caravan_party_name");
          this._cachedName.SetCharacterProperties("OWNER", this.MobileParty.LeaderHero?.CharacterObject ?? this.Owner.CharacterObject);
        }
        return this._cachedName;
      }
    }

    public override Settlement HomeSettlement => this.Settlement;

    public override Hero Leader => this._leader;

    protected internal CaravanPartyComponent(Settlement settlement, Hero owner, Hero partyLeader)
    {
      this.Settlement = settlement;
      this.Owner = owner;
      this._leader = partyLeader;
    }

    protected override void OnInitialize() => this.Owner.OwnedCaravans.Add(this);

    protected override void OnFinalize() => this.Owner.OwnedCaravans.Remove(this);

    public override void ChangePartyLeader(Hero newLeader) => this._leader = newLeader;

    public override void ClearCachedName() => this._cachedName = (TextObject) null;

    public static MobileParty CreateCaravanParty(
      Hero caravanOwner,
      Settlement spawnSettlement,
      bool isInitialSpawn = false,
      Hero caravanLeader = null,
      ItemRoster caravanItems = null,
      int troopToBeGiven = 0,
      bool isElite = false)
    {
      MobileParty party = MobileParty.CreateParty("caravan_template_" + spawnSettlement.Culture.StringId.ToLower() + "_1", (PartyComponent) new CaravanPartyComponent(spawnSettlement, caravanOwner, caravanLeader), (PartyComponent.OnPartyComponentCreatedDelegate) (mobileParty => (mobileParty.PartyComponent as CaravanPartyComponent).InitializeCaravanOnCreation(mobileParty, caravanLeader, caravanItems, troopToBeGiven, isElite)));
      if (spawnSettlement.Party.MapEvent == null && spawnSettlement.SiegeEvent == null)
      {
        party.Ai.SetMoveGoToSettlement(spawnSettlement);
        party.Ai.RecalculateShortTermAi();
        EnterSettlementAction.ApplyForParty(party, spawnSettlement);
      }
      else
        party.Ai.SetMoveModeHold();
      if (party.LeaderHero != null)
        CampaignEventDispatcher.Instance.OnHeroGetsBusy(party.LeaderHero, HeroGetsBusyReasons.BecomeCaravanLeader);
      return party;
    }

    private void InitializeCaravanOnCreation(
      MobileParty mobileParty,
      Hero caravanLeader,
      ItemRoster caravanItems,
      int troopToBeGiven,
      bool isElite)
    {
      this.InitializeCaravanProperties();
      if (troopToBeGiven == 0)
      {
        float num1 = (double) MBRandom.RandomFloat >= 0.67000001668930054 ? 1f : (float) ((1.0 - (double) MBRandom.RandomFloat * (double) MBRandom.RandomFloat) * 0.5 + 0.5);
        int num2 = (int) ((double) mobileParty.Party.PartySizeLimit * (double) num1);
        if (num2 >= 10)
          --num2;
        troopToBeGiven = num2;
      }
      PartyTemplateObject pt = isElite ? this.Settlement.Culture.EliteCaravanPartyTemplate : this.Settlement.Culture.CaravanPartyTemplate;
      mobileParty.InitializeMobilePartyAtPosition(pt, this.Settlement.GatePosition, troopToBeGiven);
      if (caravanLeader != null)
      {
        mobileParty.MemberRoster.AddToCounts(caravanLeader.CharacterObject, 1, true);
      }
      else
      {
        CharacterObject character1 = CharacterObject.All.First<CharacterObject>((Func<CharacterObject, bool>) (character => character.Occupation == Occupation.CaravanGuard && character.IsInfantry && character.Level == 26 && character.Culture == mobileParty.Party.Owner.Culture));
        mobileParty.MemberRoster.AddToCounts(character1, 1, true);
      }
      mobileParty.ActualClan = this.Owner.Clan;
      mobileParty.Party.SetVisualAsDirty();
      mobileParty.InitializePartyTrade(10000 + (this.Owner.Clan == Clan.PlayerClan ? 5000 : 0));
      if (caravanItems != null)
      {
        mobileParty.ItemRoster.Add((IEnumerable<ItemRosterElement>) caravanItems);
      }
      else
      {
        float num = 10000f;
        ItemObject itemObject1 = (ItemObject) null;
        foreach (ItemObject itemObject2 in (List<ItemObject>) Items.All)
        {
          if (itemObject2.ItemCategory == DefaultItemCategories.PackAnimal && !itemObject2.NotMerchandise && (double) itemObject2.Value < (double) num)
          {
            itemObject1 = itemObject2;
            num = (float) itemObject2.Value;
          }
        }
        if (itemObject1 == null)
          return;
        mobileParty.ItemRoster.Add(new ItemRosterElement(itemObject1, (int) ((double) mobileParty.MemberRoster.TotalManCount * 0.5)));
      }
    }

    private void InitializeCaravanProperties() => this.MobileParty.Aggressiveness = 0.0f;

    public override void GetMountAndHarnessVisualIdsForPartyIcon(
      PartyBase party,
      out string mountStringId,
      out string harnessStringId)
    {
      string str = party.MapFaction?.Culture?.StringId ?? string.Empty;
      if (str == "aserai" || str == "khuzait")
      {
        mountStringId = "camel";
        if (party.Index % 2 == 0)
          harnessStringId = "camel_saddle_a";
        else
          harnessStringId = "camel_saddle_b";
      }
      else
      {
        mountStringId = "mule";
        switch (party.Index % 3)
        {
          case 0:
            harnessStringId = "mule_load_a";
            break;
          case 1:
            harnessStringId = "mule_load_b";
            break;
          default:
            harnessStringId = "mule_load_c";
            break;
        }
      }
    }

    public static void TransferCaravanOwnership(
      MobileParty caravan,
      Hero newOwner,
      Settlement homeSettlement)
    {
      CaravanPartyComponent caravanPartyComponent = new CaravanPartyComponent(homeSettlement, newOwner, caravan.LeaderHero);
      caravan.PartyComponent = (PartyComponent) caravanPartyComponent;
      caravanPartyComponent.InitializeCaravanProperties();
      caravan.Party.SetVisualAsDirty();
    }
  }
}
